package com.design.util.moveBox;

import com.design.game.MoveBox;
import com.design.method.error.GameLogError;
import com.design.util.Console;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class GameLog {
    public boolean moving = true;
    private final ArrayList<int[]> logs = new ArrayList<>();
    private final File file;
    private int index = 0;
    public GameLog(File file)  {
        if(!file.isFile()){
            this.moving = false;
        }
        this.file = file;
        BufferedReader reader = null;
        try{
             reader = new BufferedReader(new FileReader(file));
            String str;
            while((str = reader.readLine()) != null){
                String[] strings = str.split("\\|");
                if(strings.length != 2){
                    continue;
                }
                this.logs.add(new int[]{
                        Integer.parseInt(strings[0]),
                        Integer.parseInt(strings[1])
                });
            }
        } catch (FileNotFoundException e) {
            Console.error("日志文件读取失败");
        } catch (IOException e) {
            Console.error("读取行出错");
        } finally{
            try{
                if(reader != null){
                    reader.close();
                }
            } catch (IOException e) {
                Console.warning("日志文件流关闭失败");
            }
        }
    }
    public void remove(){
        if(!this.file.delete()){
            Console.warning("日志删除失败");
        };
        this.logs.clear();
    }
    public void save() throws GameLogError {
        BufferedWriter writer = null;
        try{
             writer = new BufferedWriter(new FileWriter(this.file));
            for (int[] log : this.logs) {
                writer.write(log[0] + "|" + log[1]);
                writer.newLine();
            }
        } catch (IOException e) {
            throw new GameLogError("写入日志文件失败");
        }finally{
            try{
                if(writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                Console.warning("日志文件流关闭失败");
            }

        }
    }
    public void addLog(int[] direction){
        this.logs.add(direction);
    }
    public void run(JPanel panel, MoveBox moveBox){
        if(!this.moving){
            return;
        }
        int size = this.logs.size();
        int ms = 200;//200ms执行一次
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(index >= size){
                    timer.cancel();
                    moving = false;
                    return;
                }
                panel.repaint();
                moveBox.movePlayer(logs.get(index));
                index ++;
            }
        },0,ms);
    }
}
